<template>
  <div class="nav-header clearfix" v-loading.fullscreen.lock="loading">
    <template v-if="menuPath!==null">
      <i class="el-icon-s-fold" @click="changeCollapse"></i>
      <el-breadcrumb separator="/" class="menu-path">
        <el-breadcrumb-item v-for="menu in menuPath" :key="`menu_${menu.permissionId}`">
          {{menu.name}}
        </el-breadcrumb-item>
      </el-breadcrumb>

      <div class="nav-header-personal">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            <el-avatar shape="square" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
            <el-dropdown-item v-if="unionid!==null" command="unbindWeChat">解绑微信</el-dropdown-item>
            <el-dropdown-item v-else command="bindWeChat">绑定微信</el-dropdown-item>
            <!-- <el-dropdown-item command="toIndex">首页</el-dropdown-item> -->
            <el-dropdown-item divided command="logout">登出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </template>

    <el-dialog append-to-body title="绑定微信" custom-class="sys-dialog" :close-on-click-modal="false" :visible.sync="openDialog" top="calc(50vh - 165px)"
      width="300px">
      <div style="height:270px;overflow:auto">
        <bind-we-chart v-if="openDialog" :user="user" @create-code="createCode"></bind-we-chart>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    mapGetters,
    mapActions
  } from 'vuex';
  import Storage from 'storage';

  import LoginApi from 'services/loginApi';
  import WeChartApi from 'services/weChartApi';

  import GlobalData from 'utils/globalData';
  import SystemUtil from 'utils/systemUtil';

  import BindWeChart from './weChart/bindWeChart';

  export default {
    props: {
      menuData: {
        type: Object,
        required: true
      }
    },

    computed: {
      ...mapGetters(['user'])
    },

    watch: {
      '$route'() {
        this.setMenuPath();
      }
    },

    data() {
      return {
        loading: false,
        menuPath: null,
        openDialog: false,
        timeout: null,
        unionid: null,
        code: null
      };
    },

    created() {
      let user = this.user;
      if (user.unionid !== null) {
        this.unionid = user.unionid;
        this.setMenuPath();
        return;
      }

      let bindTime = Storage.setSession('bindTime');
      if (bindTime === null) {
        this.setMenuPath();
        return;
      }

      this.loading = true;
      this.checkBingAccount().then(unionid => {
        this.setMenuPath();

        if (unionid === null) {
          this.bindAccountRunning();
        }

        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    beforeDestroy() {
      this.clearTimeout();
    },

    methods: {
      setMenuPath() {
        let menuData = this.menuData;
        let currentMenu = this.$route.path;
        let paths = menuData.getMenuPath(currentMenu);
        this.menuPath = paths;
      },

      changeCollapse() {
        let isCollapse = this.menuData.isCollapse;
        this.menuData.isCollapse = !isCollapse;
      },

      handleCommand(command) {
        if (command === 'logout') {
          this.toLogOutSystem();
        } else if (command === 'updatePassword') {
          this.toChangePassword();
        } else if (command === 'bindWeChat') {
          this.toBindWeChat();
        } else if (command === 'unbindWeChat') {
          this.toUnbindWeChat();
        }
      },

      toLogOutSystem() {
        LoginApi.logOutSystem().then(() => {
          Storage.removeLocal('authToken');
          Storage.removeLocal('refreshToken');
          Storage.removeLocal('user');
          Storage.removeSession('menus');
          window.location.href = `${SystemUtil.getProjectName()}/login`;
        });
      },

      toChangePassword() {
        this.$emit('change-password');
      },

      toBindWeChat() {
        this.openDialog = true;
      },

      createCode(code) {
        this.clearTimeout();
        this.code = code;
        Storage.setSession('bindTime', this.$moment().startOf('minute').valueOf());
        this.bindAccountRunning(code);
      },

      toUnbindWeChat() {
        this.$confirm('是否确定该账户解绑微信', '解绑').then(() => {
          this.unbindWeChat();
        }).catch(() => {});
      },

      unbindWeChat() {
        this.loading = true;
        WeChartApi.unbindAccount(this.user).then(() => {
          this.unionid = null;
          let user = _.cloneDeep(this.user);
          user.unionid = null;
          this.setUser(user);
          this.$message({
            message: '成功解绑微信',
            type: 'success'
          });
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      bindAccountRunning(code = null) {
        let bindTime = Storage.getSession('bindTime');
        if (bindTime === null) {
          return;
        }
        let nowTime = this.$moment().startOf('minute').valueOf();
        let time = nowTime - bindTime;
        if (time > 5.5 * 60 * 1000) {
          this.timeout = null;
          Storage.removeSession('bindTime');
          return;
        }
        this.timeout = setTimeout(() => {
          this.checkBingAccount(code).then(unionid => {
            this.timeout = null;
            if (code !== this.code) {
              return;
            }

            if (unionid !== null) {
              this.openDialog = false;
              this.$message({
                message: '成功绑定微信',
                type: 'success'
              });
              return;
            }
            this.bindAccountRunning(code);
          });
        }, 5000);
      },

      checkBingAccount(code = null) {
        return WeChartApi.getBindUnionid().then(res => {
          let unionid = res ? res.unionid : null;
          if (unionid !== null) {
            this.unionid = unionid;
            let user = _.cloneDeep(this.user);
            user.unionid = unionid;
            this.setUser(user);
            Storage.removeSession('bindTime');
          }
          return unionid;
        });
      },

      clearTimeout() {
        let timeout = this.timeout;
        if (timeout !== null) {
          window.clearTimeout(timeout);
          this.timeout = null;
        }
      },

      ...mapActions(['setUser'])
    },

    components: {
      BindWeChart
    }
  };

</script>

<style lang="scss" scoped>
  .nav-header {
    padding: 0 20px;

    >* {
      float: left;
    }

    .el-icon-s-fold {
      height: 100%;
      line-height: 60px;
      font-size: 30px;
      cursor: pointer;
    }

    .menu-path {
      margin-left: 10px;
      height: 100%;
      line-height: 60px;
    }

    .nav-header-personal {
      float: right;
      padding-top: 10px;
    }
  }

</style>
